//
//  MLNetworkTool.swift
//  MLSina20160624
//
//  Created by manmanlang on 16/6/27.
//  Copyright © 2016年 manmanlang. All rights reserved.
//

import UIKit
import AFNetworking

enum MethodType:String {
    case GET = "GET"
    case POST = "POST"
}
///别名
typealias SuccessClosure = (response: AnyObject?)->()
typealias FailureClosure = (error: NSError)->()
class MLNetworkTool: AFHTTPSessionManager {
    
    static let sharedNetworkTool:MLNetworkTool = {
        let tool = MLNetworkTool()
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tool
    }()
    func request(method:MethodType, urlString:String, parameter:AnyObject?, success:SuccessClosure, failure:FailureClosure) {
        if method == .GET {
            self.GET(urlString, parameters: parameter, progress: nil, success: { (_, response) in
                success(response: response)
                }, failure: { (_, error) in
                    failure(error: error)
            })
        }else {
            self.POST(urlString, parameters: parameter, progress: nil, success: { (_, response) in
                success(response: response)
                }, failure: { (_, error) in
                    failure(error: error)
            })
        }
    }

}

extension MLNetworkTool {
    
    func oauthLoadUserAccount(code:String,success:(response:AnyObject?) -> (), failure:(error:NSError) -> ()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = [
            "client_id":ML_AppKey,
            "client_secret":ML_AppSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirect_uri
        ]
        self.request(MethodType.POST, urlString: urlString, parameter: params, success: success, failure: failure)
    }
    // 请求个人信息数据
    func oauthLoadUserInfo(userAccont: MLUserAccount, success: SuccessClosure, failure: FailureClosure) {
        // 请求url
        let urlString = "https://api.weibo.com/2/users/show.json"
        // 请求参数
        let params = [
            "access_token":userAccont.access_token!,
            "uid":userAccont.uid!
        ]
        
        self.request(MethodType.GET, urlString: urlString, parameter: params, success: success, failure: failure)
        
        
    }
}
///请求首页数据
extension MLNetworkTool {
    
    func homeLoadWeiboData(sinceId:Int64, maxId: Int64, success: SuccessClosure, failure: FailureClosure){
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        //这里可以强制解包，因为如果没有登录 就不会存在数据
        let params = [
            "access_token": MLUserAccountTool.sharedTool.accessToken!,
            "since_id":"\(sinceId)",
            "max_id":"\(maxId)"
        ]
        request(.GET, urlString: urlString, parameter: params, success: success, failure: failure)
    }
}
